<!-- 规则类型与条件说明 -->
<!-- 查看,README.md 权益包配置规格 -->

<script setup lang="ts">
import useDialog from "@/hooks/useDialog";
import { TPackage } from "@/types/global";
import { Delete } from "@element-plus/icons-vue";
import DrawerMerchant from "./DrawerMerchant.vue";
import { ProInputNumber } from "@/modules/package/form";

type TRules = TPackage["coupons"][number]["rules"];

const rules = defineModel<any[]>({ default: [] });

const ruleOptions = [
  {
    value: 1,
    label: "时间规则",
    children: [
      { label: "从领取时生效", value: 1 },
      { label: "固定时间段生效 ", value: 2 },
    ],
    disabled: true,
  },
  {
    value: 2,
    label: "核销规则",
    children: [
      { label: "所属活动报名品牌可核销", value: 1, content: "activity" },
      { label: "指定品牌可核销 ", value: 2 },
      { label: "指定品牌不可核销  ", value: 3 },
      { label: "全部入驻品牌可核销 ", value: 4, content: "all" },
    ],
  },
  {
    value: 4,
    label: "支付优惠规则",
    children: [
      { label: "最低消费金额", value: 1 },
      // （折扣预留）
      // { label: "最高优惠金额", value: 2 },
    ],
  },
] as any;

const handleCreateRule = () => {
  rules.value.push({
    rule_type: "",
    rule_condition: "",
    rule_content: "",
    remark: "",
    status: 1,
    sort: 99,
  } as any);
};

// 删除规则
const removeRule = (index: number) => {
  rules.value.splice(index, 1);
};

const handleCascaderChange = (
  [type, condition]: [number, number],
  row: TPackage["coupons"][number]["rules"][number]
) => {
  row.rule_type = type;
  row.rule_condition = condition;

  row.rule_content =
    ruleOptions
      .find((e: any) => e.value === type)
      .children.find((e: any) => e.value === condition)?.content || "";
};

// 校验对应的内容是否必填
const checkRuleValidator = (row: TRules[number], callback: any) => {
  const { rule_type, rule_condition, rule_content } = row;

  if (rule_type == 1) {
    if (rule_content) {
      if (rule_condition == 1) {
        let val = Number(rule_content || 0);
        return callback(val > 0 ? undefined : new Error("请输入合法天数"));
      } else {
        return callback(
          rule_content?.length > 0
            ? undefined
            : new Error("请选择有效期起止时间")
        );
      }
    } else {
      return callback(new Error("请设置规则内容"));
    }
  }
  return callback();
};



// 选中品牌
const confirmMerchantSelection = (selection: any[]) => {
  // model.merchartList = selection;
  const ids = selection.map(({ id }) => id).join(",");
  const titles = selection.map(({ title }) => title).join(",");

  console.log("source.value", source.value);

  source.value.rule_content = ids;
  source.value.rule_content_text = titles;
  close();
};

// 删除品牌事件
// const closeMerchantTag = (index: number) => {
//   model.merchartList.splice(index, 1);
// };

// 控制抽屉
const [visible, { source, open, close }] = useDialog();
</script>

<template>
  <ElTable :data="rules">
    <ElTableColumn label="规则类型" width="300">
      <template #="{ row, $index }">
        <ElFormItem
          label-width="0"
          :prop="['model', 'rules', $index, 'rule_type']"
        >
          <ElCascader
            class="w-full"
            :options="ruleOptions"
            :model-value="[row.rule_type, row.rule_condition]"
            @change="handleCascaderChange($event, row)"
          />
        </ElFormItem>
      </template>
    </ElTableColumn>

    <ElTableColumn prop="rule_content" label="规则内容">
      <template #="{ row, $index }">
        <ElFormItem
          label-width="0"
          :prop="['model', 'rules', $index, 'rule_content']"
          :rules="{
            required: true,
            validator: (rule, val, fn) => checkRuleValidator(row, fn),
            message: '请设置规则内容',
          }"
        >
          <template v-if="row.rule_type == 1">
            <template v-if="row.rule_condition == 1">
              <div class="text-sm">有效</div>
              <ProInputNumber
                v-model="row.rule_content"
                :min="1"
                :max="9999"
                :precision="0"
                isString
              />
              <div class="text-sm">天</div>
            </template>

            <template v-else>
              <ElDatePicker
                type="daterange"
                :model-value="row.rule_content.split(',')"
                start-placeholder="有效期起"
                end-placeholder="有效期止"
                @change="(val) => (row.rule_content = val.join(','))"
              />
            </template>
          </template>

          <template v-else-if="row.rule_type == 2">
            <span v-if="[2, 3].includes(row.rule_condition)">
              <div>已选品牌：</div>
              {{ row.rule_content_text || row.rule_content }}
            </span>
            <span v-else>
              {{
                row.rule_condition == 1
                  ? "所属活动报名品牌可核销"
                  : "全部入驻品牌可核销"
              }}
            </span>
          </template>

          <template v-else-if="row.rule_type == 4">
            <ProInputNumber
              v-model="row.rule_content"
              :min="1"
              :max="9999"
              :precision="2"
              prefix="¥"
              isString
            />
          </template>
        </ElFormItem>
      </template>
    </ElTableColumn>

    <ElTableColumn label="状态" prop="status" width="70">
      <template #="{ row }">
        <ElFormItem label-width="0">
          <ElSwitch
            v-model="row.status"
            inline-prompt
            active-text="可用"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="2"
          />
        </ElFormItem>
      </template>
    </ElTableColumn>

    <ElTableColumn label="备注">
      <template #="{ row }">
        <ElFormItem label-width="0">
          <ElInput v-model="row.remark" type="textarea" />
        </ElFormItem>
      </template>
    </ElTableColumn>

    <ElTableColumn width="140">
      <template #header>
        <div class="text-right">
          <ElButton type="primary" @click="handleCreateRule"
            >添加规则
          </ElButton>
        </div>
      </template>

      <template #="{ row, $index }">
        <div class="text-right">
          <ElButton
            v-if="row.rule_type == 2 && [2, 3].includes(row.rule_condition)"
            type="primary"
            size="small"
            plain
            @click="open(row)"
            >选择品牌</ElButton
          >
          <ElButton
            type="danger"
            circle
            :icon="Delete"
            size="small"
            @click="removeRule($index)"
          />
        </div>
      </template>
    </ElTableColumn>
  </ElTable>

  <DrawerMerchant
    v-model="visible"
    :ids="source?.rule_content"
    @selection="confirmMerchantSelection"
  />
</template>
